package com.smforj.ssm.mina.client;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class LambSocketClient implements ISocketClient,IlambSocketMessage{

	private String ip = "127.0.0.1";//服务器地址   
	private int port = 8000;//服务器端口号  
    private String message;
    private boolean isShutdown = false; 
  
    public LambSocketClient(){  
    }
    
    public static void main(String[] args)
    {
    	ISocketClient clent = new LambSocketClient();
    	if(clent.connect("127.0.0.1", 6789))
    	{
    		clent.send("1gdsgfdsgfd"); 
    		String revice = clent.read(); 
    		System.out.println("revice 2: "+revice);
    	} 
    }
	/**
	 * 连接服务器
	 * @param ip 地址
	 * @param port 端口
	 * @return true or false
	 */
    public boolean connect(String ip,int port)
    {
    	this.ip = ip;
    	this.port = port;
    	return init();
    }
    
    /***
     * 初始化Client
     * @return
     * @date 2016-8-3 下午3:58:31
     */
    private boolean init()
    { 
    	System.out.println("init");
        try {  
            //实例化一个Socket，并指定服务器地址和端口  
            Socket client = new Socket(this.ip, this.port);  
            //开启两个线程，一个负责读，一个负责写  
            new Thread(new ReadHandlerThread(client,this)).start();  
            new Thread(new WriteHandlerThread(client,this)).start();  
            return true;
        } catch (Exception e) {  
            e.printStackTrace(); 
            return false;
        }
    }
	/**
	 * 发送信息
	 * @param msg 消息
	 * @return true or false
	 */
    public boolean send(String msg)
    {
    	System.out.println("send: " +msg);
    	setMessage(msg);
    	return true;
    } 
    
	@Override
	public void setMessage(String msg) {
		this.message = msg;
	}

	@Override
	public String getMessage() {
		return message;
	}

	@Override
	public boolean close() {
		return (isShutdown = true); 
	}

	@Override
	public boolean isShutdown() {
		return isShutdown;
	}

	@Override
	public String read() { 
		return getMessage();
	}  
}    
  
/*  
 *处理读操作的线程   
 */  
class ReadHandlerThread implements Runnable{  
    private Socket client; 
    private IlambSocketMessage iMessage;
    private boolean isFirst = true;
  
    public ReadHandlerThread(Socket client,IlambSocketMessage iMessage) {  
        this.client = client;  
        this.iMessage = iMessage;
    }  
  
    @Override  
    public void run() {  
        DataInputStream dis = null;  
        try {  
        	isFirst = false;
            while(true){  
            	if(client.isConnected() && !client.isInputShutdown())
            	{
	                //读取服务器端数据    
	                dis = new DataInputStream(client.getInputStream());  
	                String receive = dis.readUTF();  
	        		System.out.println("receive: "+receive);
	                if(receive != null && receive.length() > 0)
	                	iMessage.setMessage(receive);  
            	}
            	Thread.sleep(200); 
				if(!isFirst && iMessage.isShutdown())
					break;
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally{  
            try {  
                if(dis != null){  
                    dis.close();  
                }  
                if(client != null){  
                    client = null;  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
}  
  
/*  
 * 处理写操作的线程  
 */  
class WriteHandlerThread implements Runnable{  
    private Socket client;  
    private IlambSocketMessage iMessage;
    private boolean isFirst = true;
  
    public WriteHandlerThread(Socket client,IlambSocketMessage iMessage) {  
        this.client = client;  
        this.iMessage = iMessage;
    }  
  
    @Override  
    public void run() {  
        DataOutputStream dos = null;  
        BufferedReader br = null;  
        try {  
        	isFirst = false;
            while(true){   
            	String msg = iMessage.getMessage();
            	if(msg != null && msg.length() > 0 && !client.isOutputShutdown() && client.isConnected())
            	{
	                //取得输出流  
	                dos = new DataOutputStream(client.getOutputStream());    
	                //发送数据  
	                dos.writeUTF(msg);  
	                
	                iMessage.setMessage(null);
	                System.out.println("write utf: "+msg);
            	} 
       		    Thread.sleep(200);
       		 if(!isFirst && iMessage.isShutdown())
					break;
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  finally{  
            try{  
                if(dos != null){  
                    dos.close();  
                }  
                if(br != null){  
                    br.close();  
                }  
                if(client != null){  
                    client = null;  
                }  
            }catch(Exception e){  
                e.printStackTrace();  
            }  
        }  
    }  
}
